#include"eventloop.h"
#include"eventloopThread.h"
#include"Thread.h"
#include<mutex>
#include<condition_variable>

EventLoopThread::EventLoopThread():m_loop(nullptr),m_thread(bind(&EventLoopThread::threadFunc,this),"EventLoopThread"){

}
EventLoopThread::~EventLoopThread(){
    if(m_loop!=nullptr){
        m_loop->quit();
    }
}
//开始loop
//为什么不直接在线程启动时就返回eventloop呢?我觉得是因为线程启动有时延,如果返回了一个nullptr, 会使程序奔溃
EventLoop* EventLoopThread::startLoop(){
    m_thread.start();
    {
        std::unique_lock<std::mutex> lock(m_mtx);
        while(m_loop==nullptr){
            m_cv.wait(lock);
        }
        return m_loop;
    }
}
void EventLoopThread::threadFunc(){
    EventLoop loop;
    {
        std::unique_lock<std::mutex> lock(m_mtx);
        m_loop=&loop;
        m_cv.notify_all();
    }
    loop.loop();
    m_loop=nullptr;
}